﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.生产计划_派单_车间.ProductPlan;
using ERP_SaaS_WinForm.生产计划_派单_车间.apiResquest;

namespace ERP_SaaS_WinForm.生产计划_派单_车间
{
    public partial class SelectPlan : Form
    {
        private DataGridView dgvPlans;
        private TextBox txtSearch;
        private Button btnSearch;
        private Button btnSelect;
        private Button btnCancel;
        private List<PlanData> planList = new List<PlanData>();
        
        // 选中的生产计划
        public PlanData SelectedPlan { get; private set; }

        public SelectPlan()
        {
            InitializeComponent();
            InitializeCustomComponents();
            LoadPlanData();
        }

        private void InitializeCustomComponents()
        {
            // 设置窗体标题和大小
            this.Text = "选择生产计划";
            this.Size = new Size(1000, 600);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建搜索面板
            Panel searchPanel = new Panel();
            searchPanel.Dock = DockStyle.Top;
            searchPanel.Height = 60;
            searchPanel.BackColor = Color.LightGray;

            // 创建搜索控件
            Label lblSearch = new Label();
            lblSearch.Text = "搜索计划:";
            lblSearch.Location = new Point(20, 20);
            lblSearch.Size = new Size(80, 20);

            txtSearch = new TextBox();
            txtSearch.Location = new Point(110, 18);
            txtSearch.Size = new Size(200, 25);
            // 移除 PlaceholderText，因为 .NET Framework 不支持此属性

            btnSearch = new Button();
            btnSearch.Text = "搜索";
            btnSearch.Location = new Point(320, 18);
            btnSearch.Size = new Size(80, 25);
            btnSearch.BackColor = Color.LightBlue;
            btnSearch.Click += BtnSearch_Click;

            // 添加搜索控件到面板
            searchPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, btnSearch });

            // 创建DataGridView
            dgvPlans = new DataGridView();
            dgvPlans.Dock = DockStyle.Fill;
            dgvPlans.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            dgvPlans.AllowUserToAddRows = false;
            dgvPlans.ReadOnly = true;
            dgvPlans.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dgvPlans.MultiSelect = false;
            dgvPlans.RowHeadersVisible = false;
            dgvPlans.BackgroundColor = Color.White;
            dgvPlans.GridColor = Color.LightGray;
            dgvPlans.BorderStyle = BorderStyle.None;
            dgvPlans.CellDoubleClick += DgvPlans_CellDoubleClick;

            // 创建按钮面板
            Panel buttonPanel = new Panel();
            buttonPanel.Dock = DockStyle.Bottom;
            buttonPanel.Height = 50;
            buttonPanel.BackColor = Color.White;

            btnSelect = new Button();
            btnSelect.Text = "选择";
            btnSelect.Size = new Size(80, 30);
            btnSelect.Location = new Point(20, 10);
            btnSelect.BackColor = Color.LightGreen;
            btnSelect.Click += BtnSelect_Click;

            btnCancel = new Button();
            btnCancel.Text = "取消";
            btnCancel.Size = new Size(80, 30);
            btnCancel.Location = new Point(120, 10);
            btnCancel.BackColor = Color.LightGray;
            btnCancel.Click += BtnCancel_Click;

            // 添加按钮到面板
            buttonPanel.Controls.AddRange(new Control[] { btnSelect, btnCancel });

            // 添加控件到窗体
            this.Controls.Add(dgvPlans);
            this.Controls.Add(buttonPanel);
            this.Controls.Add(searchPanel);
        }

        private async void LoadPlanData()
        {
            try
            {
                btnSearch.Enabled = false;
                btnSearch.Text = "加载中...";

                var response = await ApiRequestHelper.GetAsync<ApiResponse>("api/Plan/GetPlan");

                if (response.Success && response.Data?.code == 200 && response.Data.data != null)
                {
                    planList = response.Data.data;
                    SetupDataGridView();
                    LoadDataToGrid(planList);
                }
                else
                {
                    var errorMsg = response.Data?.msg ?? response.Message;
                    ApiRequestHelper.ShowError($"获取数据失败: {errorMsg}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnSearch.Enabled = true;
                btnSearch.Text = "搜索";
            }
        }

        private void SetupDataGridView()
        {
            dgvPlans.Columns.Clear();

            // 添加列并设置标题
            dgvPlans.Columns.Add("planId", "计划ID");
            dgvPlans.Columns.Add("planCode", "计划编号");
            dgvPlans.Columns.Add("planName", "计划名称");
            dgvPlans.Columns.Add("productName", "产品名称");
            dgvPlans.Columns.Add("specification", "规格型号");
            dgvPlans.Columns.Add("unitName", "单位");
            dgvPlans.Columns.Add("planNum", "计划数量");
            dgvPlans.Columns.Add("planStart", "计划开工时间");
            dgvPlans.Columns.Add("planEnd", "计划完工时间");

            // 设置列宽
            dgvPlans.Columns["planId"].Width = 80;
            dgvPlans.Columns["planCode"].Width = 120;
            dgvPlans.Columns["planName"].Width = 150;
            dgvPlans.Columns["productName"].Width = 120;
            dgvPlans.Columns["specification"].Width = 120;
            dgvPlans.Columns["unitName"].Width = 80;
            dgvPlans.Columns["planNum"].Width = 100;
            dgvPlans.Columns["planStart"].Width = 120;
            dgvPlans.Columns["planEnd"].Width = 120;

            // 设置标题行样式
            dgvPlans.ColumnHeadersDefaultCellStyle.BackColor = Color.LightBlue;
            dgvPlans.ColumnHeadersDefaultCellStyle.ForeColor = Color.Black;
            dgvPlans.ColumnHeadersDefaultCellStyle.Font = new Font(dgvPlans.Font, FontStyle.Bold);
            dgvPlans.ColumnHeadersHeight = 35;
            dgvPlans.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;

            // 设置交替行颜色
            dgvPlans.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
        }

        private void LoadDataToGrid(List<PlanData> plans)
        {
            dgvPlans.Rows.Clear();

            foreach (var plan in plans)
            {
                int rowIndex = dgvPlans.Rows.Add();
                dgvPlans.Rows[rowIndex].Cells["planId"].Value = plan.planId;
                dgvPlans.Rows[rowIndex].Cells["planCode"].Value = plan.planCode;
                dgvPlans.Rows[rowIndex].Cells["planName"].Value = plan.planName;
                dgvPlans.Rows[rowIndex].Cells["productName"].Value = plan.productName;
                dgvPlans.Rows[rowIndex].Cells["specification"].Value = plan.specification;
                dgvPlans.Rows[rowIndex].Cells["unitName"].Value = plan.unitName;
                dgvPlans.Rows[rowIndex].Cells["planNum"].Value = plan.planNum;
                dgvPlans.Rows[rowIndex].Cells["planStart"].Value = plan.planStart?.ToString("yyyy-MM-dd");
                dgvPlans.Rows[rowIndex].Cells["planEnd"].Value = plan.planEnd?.ToString("yyyy-MM-dd");
            }
        }

        private void BtnSearch_Click(object sender, EventArgs e)
        {
            string searchText = txtSearch.Text.Trim().ToLower();
            
            if (string.IsNullOrEmpty(searchText))
            {
                LoadDataToGrid(planList);
                return;
            }

            var filteredPlans = planList.Where(p => 
                (p.planCode?.ToLower().Contains(searchText) == true) ||
                (p.planName?.ToLower().Contains(searchText) == true) ||
                (p.productName?.ToLower().Contains(searchText) == true)
            ).ToList();

            LoadDataToGrid(filteredPlans);
        }

        private void DgvPlans_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                SelectCurrentPlan();
            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            SelectCurrentPlan();
        }

        private void SelectCurrentPlan()
        {
            if (dgvPlans.CurrentRow != null)
            {
                int planId = Convert.ToInt32(dgvPlans.CurrentRow.Cells["planId"].Value);
                SelectedPlan = planList.FirstOrDefault(p => p.planId == planId);
                
                if (SelectedPlan != null)
                {
                    this.DialogResult = DialogResult.OK;
                    this.Close();
                }
            }
            else
            {
                MessageBox.Show("请先选择一个生产计划", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
